﻿@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using System.Security.Cryptography
@using System.Text
@inject NavigationManager Navigation
@inject SignOutSessionStateManager SignOutManager

<AuthorizeView>
    <Authorized>
        <TelerikButton Icon="@IconName.User" @onclick="BeginSignOut">Log out</TelerikButton>
        <img class="k-avatar-rounded" src="@HashEmailForGravatar(context.User.Identity.Name)" />
        <a href="authentication/profile">@context.User.Identity.Name</a>
    </Authorized>
    <NotAuthorized>
        <a href="authentication/register">Register</a>
        <a href="authentication/login">Log in</a>
    </NotAuthorized>
</AuthorizeView>

@code{
    private async Task BeginSignOut(MouseEventArgs args)
    {
        await SignOutManager.SetSignOutState();
        Navigation.NavigateTo("authentication/logout");
    }

    /// Hashes an email with MD5.  Suitable for use with Gravatar profile
    /// image urls

    string HashEmailForGravatar(string email)
    {
        // Create a new instance of the MD5CryptoServiceProvider object.
        MD5 md5Hasher = MD5.Create();

        // Convert the input string to a byte array and compute the hash.
        byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(email));

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder sBuilder = new StringBuilder("https://www.gravatar.com/avatar/");

        // Loop through each byte of the hashed data
        // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

        return sBuilder.ToString();  // Return the hexadecimal string.
    }
}
